package com.edushare.common.dao;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.query.SelectQuery;

import com.edushare.common.exceptions.ProcessingException;
import com.edushare.common.mailer.UnivRegistrationMailer;
import com.edushare.common.orm.ORMInterface;
import com.edushare.common.util.CryptionUtil;
import com.edushare.common.vo.TempUsers;
import com.edushare.common.vo.Universities;
import com.edushare.common.vo.UserRoles;
import com.edushare.common.vo.Users;

public class TempUserDAO extends CayenneBasedDAO {

	public TempUserDAO(ORMInterface ormInterface) {
		super(ormInterface);
	}
	
	public void createTempUser(TempUsers tuser, String regUrl) 
	throws ProcessingException{
		tuser.setConfKey(tuser.getUserName());
		getDataContext().registerNewObject(tuser);
//		getDataContext().commitChanges();
		regUrl = regUrl+"?key="+tuser.getConfKey();
		new OutgoingEmailsDAO(ormInterface).sendMail(new UnivRegistrationMailer(tuser, regUrl).send());
		getDataContext().commitChanges();
	}
	
	@SuppressWarnings("unchecked")
	public boolean verifyConfKey(String encryptedKey) throws Exception{
		boolean isValid = false;
		String decryptedKey = CryptionUtil.decrypt(encryptedKey);
		String userName = decryptedKey.substring(0,decryptedKey.lastIndexOf("."));
		Expression e = Expression.fromString("userName = $tusername and confKey = $ckey and status = $stts");
		Map params = new HashMap();
		params.put("tusername", userName);
		params.put("ckey", decryptedKey);
		params.put("stts", new Integer(0));
		SelectQuery query = new SelectQuery(TempUsers.class, e.expWithParameters(params));
		List<TempUsers> tuserList = (List<TempUsers>)getDataContext().performQuery(query);
		if(tuserList!=null && tuserList.size() > 0){
			isValid = true;
			moveToUsersTable(tuserList.get(0));
		}
		return isValid;
	}
	
	private void moveToUsersTable(TempUsers tuser) {
		
		Users user = getDataContext().newObject(Users.class);
		user.setFirstName(tuser.getFirstName());
		user.setLastName(tuser.getLastName());
		user.setUserName(tuser.getUserName());
		user.setPassword(tuser.getPassword(), false);//Already encrypted
		user.setPhoneNo(tuser.getPhoneNo());
		user.setEmail(tuser.getEmail());
		user.setStatus(Users.INACTIVE);
		user.setCreationTimestamp(new Date(System.currentTimeMillis()));
		user.setAboutMe("");
		user.setLandingPageId(Users.LANDING_PAGE_UNIVERSITY_SETUP);
		
		Universities university = getDataContext().newObject(Universities.class);
		university.setUniversityName(tuser.getUniversityName());
		university.setUniversityDesc("");
		university.setCreationTimestamp(new Date(System.currentTimeMillis()));
		university.setStatus(Universities.UNIV_STATUS_INACTIVE);
		
		UserRoles userRole = getDataContext().newObject(UserRoles.class);
		userRole.setRoleType(UserRoles.ADMIN_ROLE);
		userRole.setUniversity(university);
		userRole.setUser(user);
		
		tuser.setStatus(1);
		
		getDataContext().commitChanges();
		getDataContext().deleteObject(tuser);
	}

	public boolean isUserNameAvailable(String userName){
		boolean isavailable = true;
		
		//1. check in users table
		Expression e = Expression.fromString("userName = $uname");
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("uname", userName);
		SelectQuery query = new SelectQuery(Users.class, e.expWithParameters(params));
		if(getDataContext().performQuery(query).size()>0)
			return false;
		
		
		//2. check in temp_users table
		e = Expression.fromString("userName = $uname");
		query = new SelectQuery(TempUsers.class, e.expWithParameters(params));
		if(getDataContext().performQuery(query).size()>0)
			return false;
		
		//3. check if it's an illegal name
		if(new LookupDAO(ormInterface).isIllegalInput(userName))
			return false;
		
		return isavailable;
	}
}
